#!/usr/bin/env python3
"""
HoneyBadger AWS部署演示脚本
此脚本演示如何在AWS上部署HoneyBadger节点
"""

import json
import os
import subprocess
import time
from datetime import datetime

def print_header(title):
    print("\n" + "="*60)
    print(f" {title}")
    print("="*60)

def print_step(step, description):
    print(f"\n[步骤 {step}] {description}")
    print("-" * 40)

def check_aws_credentials():
    """检查AWS凭证配置"""
    print_step(1, "检查AWS凭证配置")
    
    # 检查环境变量
    aws_key = os.environ.get('AWS_ACCESS_KEY_ID')
    aws_secret = os.environ.get('AWS_SECRET_ACCESS_KEY')
    aws_region = os.environ.get('AWS_DEFAULT_REGION', 'us-east-1')
    
    if not aws_key or not aws_secret:
        print("❌ AWS凭证未配置")
        print("请设置以下环境变量:")
        print("export AWS_ACCESS_KEY_ID=your_access_key")
        print("export AWS_SECRET_ACCESS_KEY=your_secret_key")
        print("export AWS_DEFAULT_REGION=us-east-1")
        return False
    
    print(f"✅ AWS凭证已配置")
    print(f"   Access Key: {aws_key[:8]}...")
    print(f"   Region: {aws_region}")
    return True

def check_ssh_key():
    """检查SSH密钥"""
    print_step(2, "检查SSH密钥")
    
    key_path = os.path.expanduser("~/.ssh/ebbflow-benchmark.pem")
    if os.path.exists(key_path):
        print(f"✅ SSH密钥已存在: {key_path}")
        return True
    else:
        print(f"❌ SSH密钥不存在: {key_path}")
        print("正在创建SSH密钥...")
        try:
            subprocess.run([
                "ssh-keygen", "-t", "rsa", "-b", "2048", 
                "-f", key_path, "-N", ""
            ], check=True)
            print(f"✅ SSH密钥创建成功: {key_path}")
            return True
        except subprocess.CalledProcessError as e:
            print(f"❌ SSH密钥创建失败: {e}")
            return False

def show_deployment_plan():
    """显示部署计划"""
    print_step(3, "部署计划")
    
    settings_file = "settings.json"
    with open(settings_file, 'r') as f:
        settings = json.load(f)
    
    instance_type = settings['instances']['type']
    regions = settings['instances']['regions']
    
    print(f"实例类型: {instance_type}")
    print(f"部署地区: {', '.join(regions)}")
    print(f"每个地区节点数: 1")
    print(f"总节点数: {len(regions)}")
    
    print("\n部署步骤:")
    print("1. 创建安全组")
    print("2. 在每个地区启动EC2实例")
    print("3. 安装依赖和编译HoneyBadger")
    print("4. 配置节点网络")
    print("5. 启动HoneyBadger节点")
    print("6. 测试节点连通性")

def simulate_deployment():
    """模拟部署过程"""
    print_step(4, "模拟部署过程")
    
    regions = ["us-east-1", "us-west-2", "eu-west-1", "ap-southeast-1"]
    instance_type = "ecs.c5.xlarge"
    
    print("🚀 开始部署HoneyBadger节点...")
    
    for i, region in enumerate(regions, 1):
        print(f"\n📍 地区 {i}: {region}")
        print(f"   实例类型: {instance_type}")
        print(f"   状态: 创建中...")
        time.sleep(1)  # 模拟创建时间
        print(f"   状态: ✅ 运行中")
        print(f"   公网IP: 模拟.{i}.{i}.{i}")
        print(f"   内网IP: 10.0.{i}.{i}.{i}")

def show_connectivity_test():
    """显示连通性测试"""
    print_step(5, "节点连通性测试")
    
    print("测试节点间连通性...")
    print("\n节点网络拓扑:")
    print("us-east-1 (10.0.1.1) ←→ us-west-2 (10.0.2.2)")
    print("     ↕                        ↕")
    print("eu-west-1 (10.0.3.3) ←→ ap-southeast-1 (10.0.4.4)")
    
    print("\n连通性测试结果:")
    regions = ["us-east-1", "us-west-2", "eu-west-1", "ap-southeast-1"]
    for i, region in enumerate(regions):
        for j, other_region in enumerate(regions):
            if i != j:
                latency = 50 + (i + j) * 10  # 模拟延迟
                print(f"  {region} → {other_region}: {latency}ms ✅")

def show_benchmark_config():
    """显示基准测试配置"""
    print_step(6, "基准测试配置")
    
    config = {
        "节点数": 4,
        "测试持续时间": "10秒",
        "交易速率": "5000 TPS",
        "批次大小": 5000,
        "协议": "HoneyBadger",
        "容错节点": 1,
        "网络延迟": "2000ms",
        "同步超时": "1000ms"
    }
    
    print("基准测试参数:")
    for key, value in config.items():
        print(f"  {key}: {value}")

def show_commands():
    """显示部署命令"""
    print_step(7, "实际部署命令")
    
    print("要实际部署HoneyBadger到AWS，请运行以下命令:")
    print("\n1. 配置AWS凭证:")
    print("   export AWS_ACCESS_KEY_ID=your_access_key")
    print("   export AWS_SECRET_ACCESS_KEY=your_secret_key")
    print("   export AWS_DEFAULT_REGION=us-east-1")
    
    print("\n2. 创建AWS密钥对:")
    print("   aws ec2 create-key-pair --key-name ebbflow-benchmark-key --query 'KeyMaterial' --output text > ~/.ssh/ebbflow-benchmark.pem")
    print("   chmod 600 ~/.ssh/ebbflow-benchmark.pem")
    
    print("\n3. 部署4个节点:")
    print("   fab create nodes=1")
    
    print("\n4. 查看实例信息:")
    print("   fab info")
    
    print("\n5. 安装依赖:")
    print("   fab install")
    
    print("\n6. 上传可执行文件:")
    print("   fab uploadexec")
    
    print("\n7. 运行基准测试:")
    print("   fab remote")
    
    print("\n8. 清理资源:")
    print("   fab kill")
    print("   fab destroy")

def main():
    """主函数"""
    print_header("HoneyBadger AWS部署演示")
    
    print("此脚本演示如何在AWS上部署HoneyBadger BFT协议")
    print("用于在4个不同地区进行分布式测试")
    
    # 检查配置
    aws_ok = check_aws_credentials()
    ssh_ok = check_ssh_key()
    
    # 显示部署计划
    show_deployment_plan()
    
    # 模拟部署
    simulate_deployment()
    
    # 显示连通性测试
    show_connectivity_test()
    
    # 显示基准测试配置
    show_benchmark_config()
    
    # 显示实际命令
    show_commands()
    
    print_header("部署演示完成")
    
    if not aws_ok:
        print("⚠️  注意: 需要配置有效的AWS凭证才能实际部署")
    
    print("📋 下一步:")
    print("1. 配置AWS凭证")
    print("2. 运行 fab create nodes=1 创建实例")
    print("3. 运行 fab install 安装依赖")
    print("4. 运行 fab remote 进行基准测试")

if __name__ == "__main__":
    main()

